// pages/individual/individual.js
import {
    findWeekStockByDate,
    // 获取场次
    findWeekStockByDay,
    //个人预约提交
    bookNow,
    //获取手机号
    sendSmsCode,
    //获取用户列表
    findTravelerInfos,
    //删除用户列表
    deleteById,
    HomeList
} from "../../api/home.js";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        checked1: "阅读并同意以上内容",
        checked2: "已阅读并同意",
        checked: false,
        //倒计时秒数
        otime: 5,
        // 接收倒计时的id
        timer: null,
        show: true,
        text: "",
        dizhi: "",
        kaiguan: "",
        thenimg: "",
        visitingInformation: "",
        newtime: '',
        closeArr: [],
        sms: "",
        smssms: "",
        ZQindex: 0,
        times: '',
        tabs: [1, 2, 3, 4, 5, 6, 7],
        day: ["一", "二", '三', "四", "五", "六", "日"],
        week: [],
        activeid: '',
        newdata: "",
        //每次切换不同的日期的数据
        meidata: "",
        Ticket: "",
        ex: [],
        //点击切换重新赋值
        newex: [],
        activeids: '',
        singleLimit: 0,
        singleChildLimit: 0,
        yonghuLsit: [],
        status: 0,
        yonghuArrs: [],
        sessionTime: '',
        travelDate: "",
        Selecte: '',
        delete1: 0,
        yonghuArrs1: [],
        tel: "",
        code: "",
        stockNum: '',
        dayType: 0,
        countDownNum: '60',
        adultFlagwei: 0,
        temporaryClosureSwitch: '',
        personalAppointmentSwitch: ''
    },
    //验证码倒计时
    countDown: function () {
        var _this = this;
        var countDownNum = _this.data.countDownNum; // 获取倒计时初始值
        var timer = setInterval(function () {
            countDownNum -= 1;
            _this.setData({
                countDownNum: countDownNum
            })
            if (countDownNum <= -1) {
                clearInterval(timer);
                // 取消置顶的setInterval函数将要执行的代码
                _this.setData({
                    countDownNum: 60,
                })
            }
        }, 1000)
    },
    onChange(event) {
        this.setData({
            checked: event.detail,
            // checked:true
        });
    },
   
    rightNow() {
        if (this.data.checked == true) {
            this.setData({
                show: false
            })
        } else {
            wx.showModal({
                title: "温馨提示",
                content: "请认真阅读以上预约须知内容后，并勾选已阅读同意"
            })
        }

    },
    // 轮询展示倒计时的方法
    pollFunc() {
        let omit = this.data.otime

        const timer = setInterval(() => {
            if (omit === 0) {
                clearInterval(this.data.timer)
            }
            this.setData({
                otime: omit--
            })

        }, 1000);
        this.setData({
            show: true
        })

        this.setData({
            timer
        })
    },
    //点击删除
    delelist(e) {
        console.log(e);
        const index = e.currentTarget.dataset.index;
        console.log(this.data.yonghuLsit[index]);
        console.log(this.data.yonghuLsit[index]);
        console.log(index);

        // console.log(this.data.yonghuList[index]);
        // console.log(this.data.yonghuList[index]);
        let _this = this
        wx.showModal({
            title: '确定删除参观者' + _this.data.yonghuLsit[index].name + "?",
            confirmColor: '#E34D59',
            success(res) {
                if (res.confirm) {
                    deleteById({
                        id: _this.data.yonghuLsit[index].id
                    }).then(res => {
                        console.log(res);
                        if (res.code == 1000) {
                            wx.showLoading({
                                title: '加载中',
                            })
                            findTravelerInfos().then(res => {
                                console.log(res);
                                if (res.code == 1000) {
                                    _this.setData({
                                        yonghuLsit: res.data
                                    })
                                    wx.hideLoading({
                                        success: (res) => {},
                                    })
                                }
                            })
                        } else {
                            wx.showModal({
                                title: "温馨提示",
                                cancelColor: res.data.code,
                            })
                        }
                    })

                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },
    //点击短信验证码
    bintap(e) {
        console.log(e.detail);
        this.setData({
            tel: e.detail
        })
    },
    //点击发送短息
    btntel() {
        let _this = this
        console.log(this.data.tel.length == 11);
        const tel = /^((13[0-9])|(14[5-9])|(15([0-3]|[5-9]))|(16[6-7])|(17[1-8])|(18[0-9])|(19[1|3])|(19[5|6])|(19[8|9]))\d{8}$/
        const phone = tel.test(this.data.tel)
        if (phone) {
            sendSmsCode({
                phone: this.data.tel
            }).then(res => {
                console.log(res);
                _this.countDown()
                if (res.code != 1000) {
                    // console.log(res.data.msg);
                    wx.showModal({
                        title: res.data.msg,
                    })
                }
            })
        } else {
            wx.showToast({
                title: '手机号格式错误',
                icon: "error"
            })
        }

    },
    //验证码的输入框
    bintscode(e) {
        // console.log(e.detail);
        this.setData({
            code: e.detail
        })
        // console.log(e.detail);
    },
    //点击添加人员列表
    addrenyuan() {
        wx.navigateTo({
            url: '/pages/add_commit/add_commit',
        })
    },
    //点击删除
    delete() {
        this.setData({
            delete1: 1
        })
    },
    //删除然后再次点击取消
    deleteshow() {
        this.setData({
            delete1: 0
        })
    },
    //返回上一页
    onClickLeft() {
        wx.removeStorageSync('indexArr')
        wx.navigateBack({
            delta: 1,
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    // 选择时间段
    activess(e) {
        console.log(e);
        const index = e.currentTarget.dataset.id
        this.setData({
            activeids: index,
        })
        console.log("点击切换时间并且拿到", this.data.newex[index]);
        this.setData({
            sessionTime: this.data.newex[index].sessionTime,
            stockNum: this.data.newex[index].stockNum,
            dayType: this.data.newex[index].dayType
        })
        console.log(this.data.dayType);
    },
    active(e) {
        console.log(this.data.newtime, "我是dj喜羊羊");
        console.log(e, "我是选中");
        const index = e.currentTarget.dataset.id
        var meidatas = this.data.ex[index].travelDate
        //后台设置提前几天
        var date2 = Number(this.data.newtime) * (1000 * 60 * 60 * 24)
        //进来默认选中的
        var date = new Date(this.data.Selecte);
        var time1 = date.getTime();
        console.log(time1);
        //切换时间的日期
        var date = new Date(meidatas);
        var time2 = date.getTime();


        if (time2 - time1 < date2) {
            wx.showModal({
                title: "温馨提示",
                content: "个人预约需要提前" + this.data.newtime + "天"
            })
            return
        }

        this.setData({
            activeid: index,
            newdata: this.data.ex[index].travelDate.substring(0, 7),
            meidata: this.data.ex[index].travelDate
        })
        //点击切换天的时候把每一天给他传过去
        console.log("切换拿到当天入馆的日期", this.data.ex[index]);
        this.setData({
            travelDate: this.data.ex[index].travelDate,
            // stockNum
        })
        console.log(this.data.meidata);
        this.onhelp(this.data.meidata)

    },
    //选择用户
    xuanzhong(e) {
        console.log(this.data.yonghuLsit, "大家好");
        console.log(e)
        const yonghuArr = [];
        const index = e.currentTarget.dataset.id
        let indexArr = wx.getStorageSync('indexArr') || []
        const chooseIndex = indexArr.indexOf(index)
        if (chooseIndex !== -1) {
            indexArr.splice(chooseIndex, 1)
        } else {
            indexArr.push(index)
        }
        indexArr = new Set(indexArr)
        wx.setStorageSync('indexArr', [...indexArr])
        console.log(index, "88888");
        console.log(this.data.yonghuLsit[index].status);


        if (this.data.yonghuLsit[index].status == 1) {
            this.data.yonghuLsit[index].status = 0

        } else if (this.data.yonghuLsit[index].status == 0) {
            this.data.yonghuLsit[index].status = 1
        }
        console.log(this.data.yonghuLsit[index]);
        this.setData({
            yonghuLsit: this.data.yonghuLsit
        })
        this.data.yonghuLsit.map((item) => {
            if (item.status == 1) {
                return yonghuArr.push(item)
            }
        })
        this.setData({
            yonghuArrs1: yonghuArr
        })
        console.log(this.data.yonghuArrs1, "我是选中的");

    },
    inBlacklist(e){
        console.log(e);
        const index = e.currentTarget.dataset.id
        //这玩意又成一个大数组了
        console.log(this.data.yonghuLsit[index]);
        wx.showModal({
            title:"温馨提示",
          cancelColor: '#377FF6',
          content: '用户:' + this.data.yonghuLsit[index].name + '被拉入黑名单,原因是“' +this.data.yonghuLsit[index].reason + "”" ,
        })
    },
    //点击编辑
    bianji(e) {
        console.log(e);
        const index = e.currentTarget.dataset.index
        //这玩意又成一个大数组了
        console.log(this.data.yonghuArrs1[index]);
        let username = this.data.yonghuArrs1[index].name;
        let cardNumber = this.data.yonghuArrs1[index].cardNum;
        let certType = this.data.yonghuArrs1[index].certType;
        let faceUrl = this.data.yonghuArrs1[index].faceUrl;
        let phone = this.data.yonghuArrs1[index].phone;
        let status = this.data.yonghuArrs1[index].status;
        let id = this.data.yonghuArrs1[index].id;
        let adults = this.data.yonghuArrs1[index].adults

        wx.navigateTo({
            url: '/pages/addcommits/addcommits?id=' + id + '&username=' + username + '&cardNumber=' + cardNumber + '&certType=' + certType + '&faceUrl=' + faceUrl + '&phone=' + phone + '&status=' + status + "&adults=" + adults,
        })

        //这拼接  不是拼接的问题 是我在找最后点确认 他为社么修改的是第一个
    },
    //预约已满
    buybtn0() {
        wx.showToast({
            title: '预约已满',
            icon: "none"
        })
    },
    //点击立即预约
    buybtn1() {
        console.log(this.data.yonghuArrs1);
        // console.log(this.data.singleLimit , "我是固定的人数");
        // console.log(this.data.yonghuLsit);
        // console.log(this.data.singleChildLimit,"我是未成年");
        // console.log(this.data.sessionTime);
        // console.log(this.data.travelDate);
        // console.log(this.data.yonghuArrs1.length, '我是选中人数');
        // debugger
        let arrlist = this.data.yonghuArrs1.filter((item) => {
            return item.adults === false
        })


        // console.log(arrlist, "我是条件");
        // this.data.yonghuArrs1.filter((item) => item.audltFlag == false)
        // console.log(this.data.yonghuArrs1.filter((item) => item.audltFlag == false));
        if (this.data.yonghuArrs1 == "") {
            wx.showToast({
                title: '请选择用户',
                icon: "error"
            })
        } else if (this.data.tel == "") {
            wx.showToast({
                title: '请输入联系手机',
                icon: "error"
            })
        } else if (this.data.code == "") {
            wx.showToast({
                title: '请输入验证码',
                icon: "error"
            })
        } else {
            wx.showLoading({
                title: '加载中',
            })
            //判断用户列表均为身份证的 再去判断是否有未成年
            const flagflag = this.data.yonghuArrs1.every((items) => {
                return items.certType === "身份证"
            })
            //均为身份证的
            if (flagflag) {
                const flage = this.data.yonghuArrs1.find(item => {
                    return item.adults === true
                })
                if (flage === undefined) {
                    wx.hideLoading({})
                    wx.showModal({
                        title: "温馨提示",
                        content: "预约时至少要包含一名成年人",
                        cancelColor: '#377FF6',
                    })

                } else if (flage.adults) {
                    const visitPeople = []
                    this.data.yonghuArrs1.forEach(item => {
                        visitPeople.push({
                            cardNum: item.cardNum,
                            certType: item.certType,
                            faceUrl: item.faceUrl,
                            name: item.name,
                            phone: item.phone
                        })
                    })
                    bookNow({
                        dayType: this.data.dayType,
                        code: this.data.code,
                        codePhone: this.data.tel,
                        sessionTime: this.data.sessionTime,
                        travelDate: this.data.travelDate,
                        visitPeople,
                    }).then((res) => {
                        console.log(res);
                        wx.hideLoading({})
                        if (res.code == 1000) {
                            this.setData({
                                sms: "",
                                smssms: ''
                            })
                            wx.navigateTo({
                                url: '/pages/gerenoderok/gerenoderok?id=' + res.data.id,
                            })
                        } else {
                            wx.showModal({
                                title: res.data.msg,
                            })
                        }
                    })
                }
                //选择其他类型的
            } else {
                // debugger
                console.log(this.data.yonghuArrs1);
                //定义一个数组，把所选的用户是身份证的拿出来再去比较
                const certTypesArray = []
                this.data.yonghuArrs1.forEach((item) => {
                    console.log(item.certType);
                    if (item.certType === "身份证") {
                        certTypesArray.push(item)
                    }
                })
                console.log(certTypesArray.length);
                const certTypeevery = certTypesArray.find((item) => {
                    return item.adults === true
                })
                console.log(certTypeevery);
                // return
                if (certTypesArray.length == 0) {
                    const visitPeople = []
                    this.data.yonghuArrs1.forEach(item => {
                        visitPeople.push({
                            cardNum: item.cardNum,
                            certType: item.certType,
                            faceUrl: item.faceUrl,
                            name: item.name,
                            phone: item.phone
                        })
                    })
                    bookNow({
                        dayType: this.data.dayType,
                        code: this.data.code,
                        codePhone: this.data.tel,
                        sessionTime: this.data.sessionTime,
                        travelDate: this.data.travelDate,
                        visitPeople,
                    }).then((res) => {
                        console.log(res);
                        wx.hideLoading({})
                        if (res.code == 1000) {
                            this.setData({
                                sms: "",
                                smssms: ''
                            })
                            wx.navigateTo({
                                url: '/pages/gerenoderok/gerenoderok?id=' + res.data.id,
                            })
                        } else {
                            wx.showModal({
                                title: res.data.msg,
                            })
                        }
                    })
                    return
                }
                if (certTypeevery == undefined) {
                    wx.hideLoading({})
                    wx.showModal({
                        title: "温馨提示",
                        content: "预约时至少要包含一名成年人",
                        cancelColor: '#377FF6',
                    })
                } else {
                    const visitPeople = []
                    this.data.yonghuArrs1.forEach(item => {
                        visitPeople.push({
                            cardNum: item.cardNum,
                            certType: item.certType,
                            faceUrl: item.faceUrl,
                            name: item.name,
                            phone: item.phone
                        })
                    })
                    bookNow({
                        dayType: this.data.dayType,
                        code: this.data.code,
                        codePhone: this.data.tel,
                        sessionTime: this.data.sessionTime,
                        travelDate: this.data.travelDate,
                        visitPeople,
                    }).then((res) => {
                        console.log(res);
                        wx.hideLoading({})
                        if (res.code == 1000) {
                            this.setData({
                                sms: "",
                                smssms: ''
                            })
                            wx.navigateTo({
                                url: '/pages/gerenoderok/gerenoderok?id=' + res.data.id,
                            })
                        } else {
                            wx.showModal({
                                title: res.data.msg,
                            })
                        }
                    })
                }
                wx.hideLoading({})
            }
        }
    },
    //获取每天的场次，this.data.meidata是我们默认选中的天，然后和点击选中的天
    //   console.log(this.data.meidata);
    //把这个接口写成一个方法 因为要点击切换时间
    onhelp(day) {
        findWeekStockByDay({
            bookDate: day
        }).then(res => {
            console.log(res);
            this.setData({
                newex: res.data.sessionTimes,
                // stockNum:res.data.sessionTimes.stockNum
            })
            //获取每天场次的第一位
            const act = this.data.newex.findIndex(item => !item.sessionTimes)
            console.log(act);
            if (act > -1) {
                this.setData({
                    activeids: act,
                })
            }
            console.log(this.data.newex);
            // console.log("//////////////////////拿到入馆时间", this.data.newex[act]);
            this.setData({
                sessionTime: this.data.newex[act].sessionTime,
                stockNum: this.data.newex[act].stockNum,
                dayType: this.data.newex[act].dayType
            })
            console.log("555555555555");
            console.log(this.data.stockNum, '我是默认选中的人数');
            console.log(this.data.dayType);
        })
    },
    onLoad(options) {
        this.pollFunc()
        console.log("woshi2222222222222222222");
        // console.log(this.data.stockNum);
        HomeList().then((res) => {
            console.log(res);
            if (res.code == 1000) {
                wx.hideLoading({
                    success: (res) => {},
                })
                wx.setStorageSync('lat', res.data.lat)
                wx.setStorageSync('lng', res.data.lng)
                this.setData({
                    visitingInformation: res.data.bulletin,
                    text: res.data.about,
                    dizhi: res.data.address,
                    thenimg: res.data.pic,
                    kaiguan: res.data.summerOpeningClosingTime
                })
            } else {
                wx.showModal({
                    title: res.data.msg,
                })
            }
        })
        //进到这个页面要传入的时间
        var a = (new Date().getMonth() + 1) < 10 ? "0" + (new Date().getMonth() + 1) : (new Date().getMonth() + 1)
        var b = new Date().getDate() < 10 ? "0" + new Date().getDate() : new Date().getDate()
        var tiem = new Date().getFullYear() + "-" + a + "-" + b
        let tiemss = tiem.substring(0, 7);
        this.setData({
            times: tiemss,
        })
        //获取场次
        //进来请求接口然后拿到 是当天的
        wx.showLoading({
            title: '加载中',
        })
        findWeekStockByDate({
            "bookDate": tiem
        }).then((res) => {
            console.log(res, "我是个人");
            this.setData({
                newtime: res.data.advanceDay,
                singleLimit: res.data.singleLimit,
                singleChildLimit: res.data.singleChildLimit,
                temporaryClosureSwitch: res.data.temporaryClosureSwitch,
                personalAppointmentSwitch: res.data.personalAppointmentSwitch,
            })
            //写俩个空数组
            var arr = []
            var arr2 = []
            res.data.oneWeekDateVos.forEach(function (e) {
                arr2.push(e.travelDate.substring(e.travelDate - 2))
                arr.push(e.week)
            })
            var object = this.data.tabs.indexOf(arr[0])
            let a = this.data.day.splice(object, this.data.tabs.length)
            let b = this.data.day.splice(0, object)
            let c = a.concat(b)
            const time = res.data.oneWeekDateVos[res.data.oneWeekDateVos.length - 1].travelDate
            let date = new Date(time)
            const {
                closeArr
            } = this.data
            for (let i = 0; i < 7 - res.data.oneWeekDateVos.length; i++) {
                date.setDate(date.getDate() + 1)
                closeArr.push((date.getDate().toString()).padStart(2, '0'))
                console.log(date.getDate())
            }
            console.log(closeArr);
            this.setData({
                week: c,
                ex: res.data.oneWeekDateVos,
                closeArr
            })
            // 寻找到第一个不闭馆的元素
            const active = this.data.ex.findIndex(item => !item.isClose)
            //    如果找到了进行赋值，因为要考虑到是不是都闭馆了
            // console.log(active);
            //id是这个数组得下标对应的
            if (active > -1) {
                this.setData({
                    activeid: active,
                })
            }
            console.log("拿到当天入馆的日期 我是当天入馆时间", this.data.ex[active]);
            this.setData({
                Selecte: this.data.ex[active].travelDate,
                travelDate: this.data.ex[active].travelDate,
                newdata: this.data.ex[active].travelDate.substring(0, 7),
                //获取每天的场次
                meidata: this.data.ex[active].travelDate
            })
            this.onhelp(this.data.meidata)
            wx.hideLoading({})
        })
        // //获取用户列表
        // findTravelerInfos().then(res => {
        //     console.log(res.data, "我是默认的人员");
        //     if (res.code == 1000) {
        //         this.setData({
        //             yonghuLsit: res.data
        //         })
        //         this.data.yonghuLsit.map(item => {
        //             item.status = 0
        //         })
        //     }
        //     console.log(this.data.yonghuLsit);
        // })
        // this.setData({
        //     yonghuLsit: wx.getStorageSync('personInfoArr')
        // })


    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        findTravelerInfos().then(res => {
            console.log(res.data, "我是默认的人员");
            let {
                yonghuArrs1
            } = this.data
            if (res.code == 1000) {
                res.data.map(item => {
                    item.status = 0
                })
                const indexArr = wx.getStorageSync('indexArr') || []
                console.log(res.data);
                yonghuArrs1 = []
                indexArr.forEach(item => {
                    res.data[item].status = 1
                    yonghuArrs1.push(res.data[item])
                })
                this.setData({
                    yonghuLsit: res.data,
                    yonghuArrs1
                })

            }
        })
        var a = (new Date().getMonth() + 1) < 10 ? "0" + (new Date().getMonth() + 1) : (new Date().getMonth() + 1)
        var b = new Date().getDate() < 10 ? "0" + new Date().getDate() : new Date().getDate()
        var tiem = new Date().getFullYear() + "-" + a + "-" + b
        let tiemss = tiem.substring(0, 7);
        this.setData({
            times: tiemss,
        })
        this.setData({
            yonghuLsit: wx.getStorageSync('personInfoArr')
        })
        let arr = []
        if (this.data.yonghuLsit != "") {
            this.data.yonghuLsit.map(item => {
                if (item.status === 1) {
                    arr.push(item)
                }
            })
            console.log(arr)
            this.setData({
                yonghuArrs1: arr
            })
        }
        console.log(this.data.yonghuArrs1);
        //进来请求接口然后拿到 是当天的
        findWeekStockByDate({
            "bookDate": tiem
        }).then((res) => {
            console.log(res);
            this.setData({
                singleLimit: res.data.singleLimit,
                singleChildLimit: res.data.singleChildLimit,
                temporaryClosureSwitch: res.data.temporaryClosureSwitch,
                personalAppointmentSwitch: res.data.personalAppointmentSwitch,
            })
            this.onhelp(this.data.meidata)
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        wx.removeStorageSync('indexArr')
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})